package com.education.springbootdemo.mail;

import jakarta.mail.Authenticator;
import jakarta.mail.PasswordAuthentication;
import jakarta.mail.Session;
import jakarta.mail.Transport;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeMessage;

import java.util.Properties;

public class EmailUtils {

    //发送邮件工具方法
    public static boolean sendEmail(MyEmail email ,String to, String title, String content) {

        MimeMessage mimeMessage = null;
        try {
            Properties props = new Properties();
            props.put("mail.smtp.host", email.getHost());
//            props.put("mail.smtp.host", "smtp.qq.com");
            props.put("mail.smtp.auth", email.isAuth());
            props.put("mail.smtp.ssl.enable",email.isSslenable());
            props.put("mail.user", email.getUser());
            props.put("mail.password",email.getCode());
            props.put("mail.smtp.timeout", "30000"); // 30秒超时

            Authenticator auth = new Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(email.getUser(), email.getCode());
                }
            };

            Session mailSession = Session.getInstance(props, auth);

            mimeMessage = new MimeMessage(mailSession);

        }catch (Exception e) {

            e.printStackTrace();

        }

        if(mimeMessage == null) {
            return false;
        }

        try {
            InternetAddress from = new InternetAddress(email.getUser());
            mimeMessage.setFrom(from);

            InternetAddress toAddress = new InternetAddress(to);
            mimeMessage.setRecipient(MimeMessage.RecipientType.TO,toAddress);

            mimeMessage.setSubject(title);

            mimeMessage.setContent(content,"text/html;charset=utf-8");

            Transport.send(mimeMessage);
        }catch (Exception e) {
            e.printStackTrace();
            return false;
        }

        return true;
    }
}
